package window;

import com.alibaba.fastjson.JSONObject;
import constants.TemplateType;
import cookie.ProjectCookie;
import javafx.geometry.Insets;
import javafx.geometry.Rectangle2D;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.stage.Modality;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.util.Callback;
import language.Language;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.ProjectUtil;

import java.io.File;
import java.io.IOException;

/**
 * 用一句话描述该文件作用
 *
 * @Author pengsamkee
 * create at 2016/11/15 11:21
 */
public class TemplateSettingWindow {

    private static final Logger logger = LoggerFactory.getLogger(TemplateSettingWindow.class);

    final ComboBox exportNameComboBox = new ComboBox();

    final ButtonBar templateTypeEditButtonBar = new ButtonBar();

    final TextArea templateTextArea = new TextArea("");

    final ButtonBar templateEditButtonBar = new ButtonBar();

    final ButtonBar templateSaveButtonBar = new ButtonBar();

    String templateName;

    private File templateFile;

    private File templateSourceFile;

    private final Stage stage = new Stage();

    private static final String encoding = "UTF-8";

    private ProjectCookie projectCookie;

    private String templateType;

    public void init(Stage ownerStage, String templateType) {
        this.templateType = templateType;
        this.projectCookie = ProjectCookie.getProjectCookie();

        stage.setTitle(templateType == TemplateType.CLIENT ? Language.getTranslation("client.template.setting"): Language.getTranslation("server.template.setting"));//客户端模板设置:服务端模板设置
        stage.getIcons().add(new Image("app.logo.png"));
        stage.initOwner(ownerStage);
        stage.initModality(Modality.APPLICATION_MODAL);
        stage.setWidth(1024);
        stage.setHeight(600);
        stage.setMaximized(false);
        stage.setResizable(false);

        exportNameComboBox.getItems().addAll(
                ProjectCookie.getTypes(this.projectCookie, this.templateType)
        );
        exportNameComboBox.setValue(ProjectCookie.getExportType(this.projectCookie, this.templateType));
        exportNameComboBox.setCellFactory(
                new Callback<ListView<String>, ListCell<String>>() {
                    @Override
                    public ListCell<String> call(ListView<String> param) {
                        final ListCell<String> cell = new ListCell<String>() {
                            {
                                super.setPrefWidth(80);
                            }

                            @Override
                            public void updateItem(String item, boolean empty) {
                                super.updateItem(item, empty);
                                if (item != null) {
                                    setText(item);
                                } else {
                                    setText(null);
                                }
                            }
                        };
                        return cell;
                    }
                });
        exportNameComboBox.valueProperty().addListener((observableValue, oldValue, newValue) -> updateTemplate());

        Button addTemplateButton = new Button(Language.getTranslation("add.template"), new ImageView(new Image("add_template.png")));//新增模板
        addTemplateButton.setOnMouseClicked(event -> {
            AddTemplateWindow addTemplateWindow = new AddTemplateWindow();
            addTemplateWindow.init(stage, this.templateType);
        });

        // Add buttons to the ButtonBar
        this.templateTypeEditButtonBar.getButtons().addAll(addTemplateButton);

        templateTextArea.setMinWidth(1008);
        templateTextArea.setMinHeight(480);
        templateTextArea.setWrapText(true);
        templateTextArea.setEditable(false);

        this.updateTemplate();

        this.templateSaveButtonBar.setVisible(false);
        this.templateEditButtonBar.setVisible(true);

        Button editButton = new Button(Language.getTranslation("edit.template"));//編輯
        editButton.setOnAction(e -> {
            this.templateTextArea.setEditable(true);
            this.templateTextArea.requestFocus();
            this.templateSaveButtonBar.setVisible(true);
            this.templateEditButtonBar.setVisible(false);
        });

        // Add buttons to the ButtonBar
        this.templateEditButtonBar.getButtons().addAll(editButton);

        Button saveButton = new Button(Language.getTranslation("save.template"));//保存
        saveButton.setDefaultButton(true);
        saveButton.setOnAction(e -> {
            this.templateTextArea.setEditable(false);
            this.templateSaveButtonBar.setVisible(false);
            this.templateEditButtonBar.setVisible(true);
            this.templateTextArea.requestFocus();
            this.saveTemplate();
        });

        Button cancelButton = new Button(Language.getTranslation("cancel.template"));//放棄
        cancelButton.setOnAction(e -> {
            this.templateTextArea.setEditable(false);
            this.templateSaveButtonBar.setVisible(false);
            this.templateEditButtonBar.setVisible(true);
            this.updateTemplate();
            this.templateTextArea.requestFocus();
        });

        Button resetButton = new Button(Language.getTranslation("reset.template"));//重置
        resetButton.setOnAction(e -> {
            this.resetTemplate();
            this.templateTextArea.requestFocus();
        });

        // Add buttons to the ButtonBar
        this.templateSaveButtonBar.getButtons().addAll(saveButton, cancelButton, resetButton);

        GridPane grid = new GridPane();
        grid.setVgap(8);
        grid.setHgap(8);
        grid.setPadding(new Insets(5, 5, 5, 5));
        grid.add(this.exportNameComboBox, 0, 0);
        grid.add(this.templateTypeEditButtonBar, 1, 0);
        grid.add(this.templateTextArea, 0, 1, 4, 1);
        grid.add(this.templateEditButtonBar, 3, 2);
        grid.add(this.templateSaveButtonBar, 3, 2);

        Scene scene = new Scene(new Group(), 1024, 600);
        Group root = (Group) scene.getRoot();
        root.getChildren().add(grid);
        stage.setScene(scene);

        Rectangle2D primScreenBounds = Screen.getPrimary().getVisualBounds();
        stage.setX((primScreenBounds.getWidth() - stage.getWidth()) / 2);
        stage.setY((primScreenBounds.getHeight() - stage.getHeight()) / 2);

        stage.showAndWait();
    }

    private void updateTemplate() {
        this.templateName = (String) this.exportNameComboBox.getValue();
        if (!this.templateName.equals(ProjectCookie.getExportType(this.projectCookie, this.templateType))) {
            ProjectCookie.setExportType(this.projectCookie, this.templateType, this.templateName);
            try {
                FileUtils.writeStringToFile(ProjectUtil.getCookieFile("ProjectCookie.json"), JSONObject.toJSONString(this.projectCookie), this.encoding);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        this.templateFile = ProjectUtil.getTemplateFile(this.templateType, this.templateName);
        try {
            this.templateTextArea.setText(FileUtils.readFileToString(this.templateFile, encoding));
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }

    private void saveTemplate() {
        this.templateName = (String) this.exportNameComboBox.getValue();
        this.templateFile = ProjectUtil.getTemplateFile(this.templateType, this.templateName);
        try {
            FileUtils.writeStringToFile(this.templateFile, this.templateTextArea.getText(), this.encoding);
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }

    private void resetTemplate() {
        this.templateName = (String) this.exportNameComboBox.getValue();
        this.templateFile = ProjectUtil.getTemplateFile(this.templateType, this.templateName);
        this.templateSourceFile = ProjectUtil.getSourceTemplateFile(this.templateType, this.templateName);
        try {
            String templateSourceContent = FileUtils.readFileToString(this.templateSourceFile, encoding);
            templateTextArea.setText(templateSourceContent);
            FileUtils.writeStringToFile(this.templateFile, templateSourceContent, this.encoding);
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }

}
